package cn.org.eshow.dao.hibernate;

import cn.org.eshow.bean.query.UserCouponQuery;
import cn.org.eshow.common.dao.EnhancedRule;
import cn.org.eshow.common.page.Page;
import cn.org.eshow.dao.UserCouponDao;
import cn.org.eshow.model.UserCoupon;
import org.hibernate.criterion.Order;
import org.hibernate.criterion.Restrictions;
import org.springframework.stereotype.Repository;

import java.util.List;

@Repository("userCouponDao")
public class UserCouponDaoHibernate extends GenericDaoHibernate<UserCoupon, Integer> implements UserCouponDao {


    public UserCouponDaoHibernate() {
        super(UserCoupon.class);
    }

    @Override
    public List<UserCoupon> list(UserCouponQuery query) {
        EnhancedRule rule = new EnhancedRule();
        setRule(rule, query);
        return list(rule);
    }

    @Override
    public Page<UserCoupon> search(UserCouponQuery query) {
        EnhancedRule rule = new EnhancedRule();
        setRule(rule, query);
        if (query != null) {
            rule.setOffset(query.getOffset());
            rule.setPageSize(query.pagesize);
        }
        return page(rule);
    }

    @Override
    public Long count(UserCouponQuery query) {
        EnhancedRule rule = new EnhancedRule();
        setRule(rule, query);
        return count(UserCoupon.class, rule);
    }

    public EnhancedRule setRule(EnhancedRule rule, UserCouponQuery query) {
        if (query != null) {
            if (query.startAddTime != null) {
                rule.add(Restrictions.ge("addTime", query.startAddTime));
            }
            if (query.endAddTime != null) {
                rule.add(Restrictions.le("addTime", query.endAddTime));
            }
            if (query.startUpdateTime != null) {
                rule.add(Restrictions.ge("updateTime", query.startUpdateTime));
            }
            if (query.endUpdateTime != null) {
                rule.add(Restrictions.le("updateTime", query.endUpdateTime));
            }
            if (query.state != null) {
                rule.add(Restrictions.eq("state", query.state));
            }
            if (query.enabled != null) {
                rule.add(Restrictions.eq("enabled", query.enabled));
            }
            if (query.couponId != null) {
                rule.add(Restrictions.eq("coupon.id", query.couponId));
            }
            if (query.userId != null) {
                rule.add(Restrictions.eq("user.id", query.userId));
            }
            if (query.getOrder() != null) {
                rule.addOrder(query.getDesc() ? Order.desc(query.getOrder()) : Order.asc(query.getOrder()));
            }
        }
        return rule;
    }

}
